# -*- coding: utf-8 -*-
import sys
if sys.getdefaultencoding() != 'utf-8':
    reload(sys)
    sys.setdefaultencoding('utf-8')

ADDON_ID = 'plugin.program.dmdsplayer'

import os, inspect
cwd = os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0])
sys.path[0:0] = [os.path.join(cwd, 'resources/lib')]
from xbmcswift2_patched import xbmc, log
import time
import dmds.addon

log.debug(os.environ)

def is_addon_active():
    return xbmc.getCondVisibility( "System.HasAddon(%s)" % ADDON_ID )

def get_traceback():
    from cStringIO import StringIO
    h = StringIO()
    import traceback
    traceback.print_exc(file=h)
    return h.getvalue()

def get_xbmc_boot_time():
    logfile = xbmc.translatePath('special://logpath')
    if logfile and os.path.exists(logfile):
        return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(logfile)))
    return ''

if __name__ == '__main__':
    first_time = True
    while not xbmc.abortRequested:
        try:
            if is_addon_active():
                try:
                    del run_on_startup
                except:
                    pass
                reload(dmds.addon)
                if first_time:
                    first_time = False
                    old_xbmc_boot_time = dmds.addon.plugin.get_setting('xbmc_boot_time', str, '')
                    xbmc_boot_time = get_xbmc_boot_time()
                    log.debug('get xbmc boot time: %s, recorded time: %s' % (xbmc_boot_time, old_xbmc_boot_time))
                    if xbmc_boot_time != old_xbmc_boot_time:
                        dmds.addon.startup_clear_lock()
                    dmds.addon.plugin.set_setting('xbmc_boot_time', xbmc_boot_time)
                    dmds.addon.check_ask_set_skin_background()
                dmds.addon.run_on_startup()
        except:
            log.warning(get_traceback())
        if xbmc.abortRequested:
            break
        xbmc.sleep(1000)
    log.debug('dmdsplayer service daemon exited.')
